﻿
using GameProtocol;
using GameProtocol.DTO;
using UnityEngine;


public class SocketHandShakeState : SocketStateBase
{
    private long m_SendHandShakeClientTime;//握手消息发送时间

    private const int HAND_SHAKE_TIME_OUT = 5000;//握手超时时间


    public SocketHandShakeState(SocketClient socketClient) : base(socketClient)
    {
    }

    public override void OnEnter()
    {
        base.OnEnter();
        NetDispatcher.Instance.AddEventListener(LoginProtocol.HAND_SHAKE_SRES, OnServerReturnHandShake);
        m_SocketClient.ReceiveMessage();
        ClientSendHandShake();
    }

    public override void OnUpdate()
    {
        base.OnUpdate();
        if (TimeUtil.GetTimestampMS() - m_SendHandShakeClientTime > HAND_SHAKE_TIME_OUT)//握手超时
        {
            Debug.Log("握手超时");
            m_SocketClient.Close(false);
        }
    }

    public override void OnExit()
    {
        base.OnExit();
        NetDispatcher.Instance.RemoveEventListener(LoginProtocol.HAND_SHAKE_SRES, OnServerReturnHandShake);
    }



    #region ClientSendHandShake 客户端发送握手消息
    /// <summary>
    /// 客户端发送握手消息
    /// </summary>
    private void ClientSendHandShake()
    {
        //给服务器发送唯一标识码Token
        SocketModel proto = new SocketModel();
        proto.Type = Protocol.TYPE_LOGIN;
        proto.Command = LoginProtocol.HAND_SHAKE_CREQ;
        
        string token= Utils.GetRandomString(10, true, false,true,false);
        Debug.Log("发送的："+token);
        proto.Message = token;

        m_SendHandShakeClientTime = TimeUtil.GetTimestampMS();
        m_SocketClient.Send(MSGEncodeManager.MSGEncode(proto));

        Debug.Log("客户端发送握手消息");
    }
    #endregion

    #region OnServerReturnHandShake 服务器返回握手消息
    /// <summary>
    /// 服务器返回握手消息
    /// </summary>
    /// <param name="obj"></param>
    private void OnServerReturnHandShake(object obj)
    {
        SocketModel token = obj as SocketModel;
        PlayerPrefs.SetString("pass_token", token.GetMessage<string>());
        Debug.Log("收到的消息："+ token.GetMessage<string>());
        int handShakePing = (int)((TimeUtil.GetTimestampMS() - m_SendHandShakeClientTime) / 2);
        Debug.Log("fps=" + handShakePing + "ms");
        long ServerCurrentTime = 1 + handShakePing;
        Debug.Log(GlobalInit.Instance.TimeDistance);
        GlobalInit.Instance.TimeDistance = TimeUtil.GetTimestampMS() - ServerCurrentTime;
        Debug.Log("服务器时间和客户端时间差值" + GlobalInit.Instance.TimeDistance + "ms");
        if (m_SocketClient.onConnectComplete != null)
        {
            m_SocketClient.onConnectComplete(true);
            m_SocketClient.onConnectComplete = null;
        }

        ChangeState(SocketClient.SocketState.Communicate);
    }
    #endregion
}
